package com.wyp.controller.admin;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wyp.myutils.myutils;
import com.wyp.pojo.Apartments;
import com.wyp.pojo.Questions;
import com.wyp.service.impl.ApartmentsServiceImpl;
import com.wyp.service.impl.QuestionsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin")
public class TestlibManController {

    @Autowired
    private QuestionsServiceImpl questionsService;

    @Autowired
    private ApartmentsServiceImpl apartmentsService;

    @GetMapping("/testlib_manage.html")
    public String tologin(Model model) {
        List<Apartments> apartments = apartmentsService.qureyAllApartment();
        model.addAttribute("apartments", apartments);
        return "admin/testlib/testlib_manage";
    }

    @GetMapping("/testlib_information.html/{apartmentid}")
    public String totestlibinfo(
            @PathVariable("apartmentid") int apartmentid,
            Model model,
            @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
            @RequestParam(value = "pageSize", defaultValue = "4") int pageSize
    ) {
        if (pageNum <= 0) {
            pageNum = 1;
        }
        //1.引入分页插件,pageNum是第几页，pageSize是每页显示多少条,默认查询总数count
        PageHelper.startPage(pageNum, pageSize);
        //2.紧跟的查询就是一个分页查询-必须紧跟.后面的其他查询不会被分页，除非再次调用PageHelper.startPage
        try {
            List<Map<String, Object>> questionsList = questionsService.qureyQuestionsByApartmentname(apartmentid);
            //3.使用PageInfo包装查询后的结果,5是连续显示的条数,结果list类型是Page<E>
            PageInfo<Map<String, Object>> pageInfo = new PageInfo<Map<String, Object>>(questionsList, pageSize);
            //4.使用model/map/modelandview等带回前端
            model.addAttribute("pageInfo", pageInfo);

            model.addAttribute("apartmentname", apartmentsService.qureyApartmentById(apartmentid).getApartmentname());

        } finally {
            PageHelper.clearPage(); //清理 ThreadLocal 存储的分页参数,保证线程安全
        }
        return "admin/testlib/testlib_information";
    }

    @RequestMapping("/question_qurey.html/{apartmentid}")
    public String toqureytestlibinfo(
            @PathVariable("apartmentid") int apartmentid,
            @Nullable @RequestParam("qureymessage") String qureymessage
    ) throws UnsupportedEncodingException {
        if (qureymessage != null && !(qureymessage.equals(""))) {
            qureymessage = new String(qureymessage.getBytes("utf-8"), "iso-8859-1");
            return "redirect:/admin/question_qurey.html/" + apartmentid + "/" + qureymessage;
        } else {
            return "redirect:/admin/testlib_information.html/" + apartmentid;
        }
    }

    @RequestMapping("/question_qurey.html/{apartmentid}/{qureymessage}")
    public String qureytestlibinfo(@PathVariable("apartmentid") int apartmentid,
                                   Model model,
                                   @Nullable @PathVariable("qureymessage") String qureymessage,
                                   @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                   @RequestParam(value = "pageSize", defaultValue = "4") int pageSize
    ) {
        if (pageNum <= 0) {
            pageNum = 1;
        }
        //1.引入分页插件,pageNum是第几页，pageSize是每页显示多少条,默认查询总数count
        PageHelper.startPage(pageNum, pageSize);
        //2.紧跟的查询就是一个分页查询-必须紧跟.后面的其他查询不会被分页，除非再次调用PageHelper.startPage
        try {
            if (qureymessage == null || qureymessage.equals("")) {
                List<Map<String, Object>> questionsList = questionsService.qureyAllQuestions();
                PageInfo<Map<String, Object>> pageInfo = new PageInfo<Map<String, Object>>(questionsList, pageSize);
                model.addAttribute("pageInfo", pageInfo);
                model.addAttribute("apartmentid", apartmentid);
            } else {
                List<Map<String, Object>> questionsList = questionsService.qureyQuestionsByMessage(qureymessage, apartmentid);
                //3.使用PageInfo包装查询后的结果,5是连续显示的条数,结果list类型是Page<E>
                PageInfo<Map<String, Object>> pageInfo = new PageInfo<Map<String, Object>>(questionsList, pageSize);
                //4.使用model/map/modelandview等带回前端
                model.addAttribute("pageInfo", pageInfo);
                model.addAttribute("apartmentid", apartmentid);
            }
        } finally {
            PageHelper.clearPage(); //清理 ThreadLocal 存储的分页参数,保证线程安全
        }
        return "admin/testlib/testlib_information";
    }

    @GetMapping("/question_add.html/{type}/{apartmentid}")
    public String toaddquestion(
            @PathVariable("type") int type,
            @PathVariable("apartmentid") int apartmentid,
            Model model
    ) {
        List<Apartments> apartments = apartmentsService.qureyAllApartment();
        model.addAttribute("apartments", apartments);
        model.addAttribute("type", type);
        model.addAttribute("apartmentid", apartmentid);
        return "admin/testlib/question_add";
    }

    @PostMapping("/question_add.html")
    public String addquestion(Questions questions, Model model) {
        if ((null != questions.getAnswer()) && (!questions.getAnswer().equals(""))) {
            questions.setAnswer(new myutils().delspace(questions.getAnswer()));
        }
        boolean info = questionsService.addQuestions(questions);
        return "redirect:/admin/testlib_information.html/" + questions.getApartmentid();
    }

    @GetMapping("/question_update.html/{id}")
    public String toquestupdate(
            @PathVariable("id") int id,
            Model model
    ) {
        Map<String, Object> upquestion = questionsService.qureyQuestionsByid(id);
        List<Apartments> apartments = apartmentsService.qureyAllApartment();
        model.addAttribute("apartments", apartments);
        model.addAttribute("upquestion", upquestion);
        return "admin/testlib/question_update";
    }

    @PostMapping("/question_update.html")
    public String updatequestion(Questions questions, Model model) {
        boolean info = questionsService.updateQuestions(questions);
        return "redirect:/admin/testlib_information.html/" + questions.getApartmentid();
    }

    @GetMapping("/question_mutliup.html/{apartmentid}")
    public String tomutiladdquestion(
            @PathVariable("apartmentid") int apartmentid,
            Model model
    ) {
        model.addAttribute("apartmentid", apartmentid);
        return "admin/testlib/question_mutliup";
    }
    //excel模板下载
    @RequestMapping("/downTemplate")
    public Object downTemplate(HttpServletResponse res, HttpServletRequest request) {
        ResponseEntity<InputStreamResource> response = null;
        try {
            // 要下载的文件在项目中的路径(一般放在resource下的文件夹内)
            String path = "static/template/model.xlsx";
            String fileName = path.substring(path.lastIndexOf("/") + 1);
            // 根据路径读取文件
            ClassPathResource resource = new ClassPathResource(path);
            File sourceFile =  resource.getFile();
            FileInputStream inputStream = new FileInputStream(sourceFile);
            // 设置头 和 返回包体
            HttpHeaders headers = new HttpHeaders();
            headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
            headers.add("Content-Disposition",
                    "attachment; filename=" + fileName);
            headers.add("Pragma", "no-cache");
            headers.add("Expires", "0");
            response = ResponseEntity.ok().headers(headers)
                    .contentType(MediaType.parseMediaType("application/octet-stream"))
                    .body(new InputStreamResource(inputStream));
        } catch (Exception e) {
            System.out.println(e.toString());
        }
        return response;
    }

        /**
         * 导入excel
         */
        @RequestMapping("/import")
        @ResponseBody
        public Map<String, Object> excelImport(@RequestParam(value="file")MultipartFile file){
            Map<String, Object> resultMap = new HashMap<String, Object>();
            boolean isExist;
            int result = 0;
            try {
                result = questionsService.questionMultiImport(file);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if(result > 0){
                isExist = true;
            }else{
                isExist = false;
            }
            resultMap.put("isExist", isExist);
            return resultMap;
        }
    }


